import { page, update, remove } from '@/services/client';

export default {
  namespace: 'client',

  state: {
    list: {
      data: [],
      pagination: {},
    },
    form: {
      data: {},
      visible: false,
    },
  },

  effects: {
    *fetch({ payload }, { call, put }) {
      const { data } = yield call(page, payload);
      yield put({
        type: 'list',
        payload: {
          data: data.content,
          pagination: {
            current: data.number + 1,
            pageSize: data.size,
            total: Number(data.totalElements),
          },
        },
      });
    },
    *openForm({ payload }, { put }) {
      const data = payload || {};
      yield put({
        type: 'form',
        payload: {
          data,
          visible: true,
        },
      });
    },
    *closeForm(_, { put }) {
      yield put({
        type: 'form',
        payload: {
          visible: false,
        },
      });
    },
    *update({ payload }, { call, put }) {
      yield call(update, { ...payload, scope: 'read,write,trust' });
      yield put({ type: 'closeForm' });
      yield put({ type: 'fetch' });
    },
    *remove({ payload }, { call, put }) {
      yield call(remove, payload);
      yield put({ type: 'fetch' });
    },
  },

  reducers: {
    list(state, { payload }) {
      return { ...state, list: { ...state.list, ...payload } };
    },
    form(state, { payload }) {
      return { ...state, form: { ...state.form, ...payload } };
    },
  },
};
